package com.unknowpupil.web.base.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unknowpupil.web.base.AbstractBaseDomain;
import com.unknowpupil.web.base.BaseCrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.MyMapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.Date;

/**
 * @Classname: BaseCrudServiceImpl
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/9/29 10:29
 * @Description:
 * @Version: 1.0
 */
public class BaseCrudServiceImpl<T extends AbstractBaseDomain,M extends MyMapper<T>> implements BaseCrudService<T> {

    private Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    @Autowired
    protected M mapper;

   @Override
    public boolean unique(String property, String value) {
        // 实体类的class ，但是 泛型拿不到 class
        Example example = new Example(entityClass);
        example.createCriteria().andEqualTo(property,value);
        int result = mapper.selectCountByExample(example);
        return result>0?false:true;
    }

    @Override
    @Transactional(readOnly = false)
    public T save(T domain) {
       int result = 0;
        /**
         * date获取时间式根据 jvm 调取系统 拿回来得时间 很多得服务，会导致时间戳不同 就会有意向不到得问题
         * 分布式系统不能用new Date直接获取时间 因为时间不一致 多个节点  全局时钟 myshop-service-datetime;单独得服务获取系统时间
         * 这里没有做
         */
        Date currenctDate = new Date();
        domain.setUpdated(currenctDate);
        if (domain.getId() == null){
            domain.setCreated(currenctDate);
            result = mapper.insertUseGeneratedKeys(domain);
        }
        //更新
        else {
            result = mapper.updateByPrimaryKeySelective(domain);
        }

        if(result>0){
            return domain;
        }
        //保存更新失败
        return null;
    }

    /**
     * 分页查询
     * @param doMain
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<T> page(T doMain, int pageNum, int pageSize){
       Example example = new Example(entityClass);
       example.createCriteria().andEqualTo(doMain);
       PageHelper.startPage(pageNum,pageSize);
       PageInfo<T> pageInfo = new PageInfo<>(mapper.selectByExample(example));
       return pageInfo;
    }
    @Transactional(readOnly = false)

    public int update(T t){
        return mapper.updateByPrimaryKey(t);
    }
    @Transactional(readOnly = false)

    public int delete(T t){
        return mapper.delete(t);
    }

    public T selectOne(T t){
        return mapper.selectOne(t);
    }

    public int count(T t){
        return mapper.selectCount(t);
    }


}
